package org.gim.config;

import cn.dev33.satoken.exception.NotLoginException;
import lombok.extern.slf4j.Slf4j;
import org.gim.common.CommonResult;
import org.gim.common.exection.*;
import org.gim.common.ResultStatus;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 全局异常处理
 */
@Slf4j(topic = "lml")
@RestControllerAdvice
public class GlobalExceptionAdvice {


    /**
     * 400 - Bad Request @Validated 校验错误异常处理
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public CommonResult<Void> handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) throws IOException {
        BindingResult bindingResult = e.getBindingResult();
        ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
        return CommonResult.errorResponse(objectError.getDefaultMessage(), ResultStatus.FAIL);
    }

    /**
     * 401 - Token 校验失败
     */
    @ExceptionHandler(TokenValidationException.class)
    public CommonResult handleTokenValidationException(TokenValidationException ex) {
        return CommonResult.errorResponse(ex.getMessage(), ResultStatus.ACCESS_DENIED);
    }

    /**
     * 处理 Sa-token 未登录情况
     */
    @ExceptionHandler(NotLoginException.class)
    public CommonResult handleNotLoginException(NotLoginException e) {
        return CommonResult.errorResponse("用户未登录",ResultStatus.ACCESS_DENIED);
    }

//    /**
//     * 兜底系统错误异常
//     */
//    @ExceptionHandler(Exception.class)
//    public CommonResult defaultException(Exception ex) {
//        return CommonResult.errorResponse(ex.getMessage(), ResultStatus.SYSTEM_ERROR);
//    }


    /**
     * 打印异常信息
     */
    public static String getMessage(Exception e) {
        String swStr = null;
        try (StringWriter sw = new StringWriter();
             PrintWriter pw = new PrintWriter(sw)) {
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
            swStr = sw.toString();
        } catch (IOException ex) {
            ex.printStackTrace();
            log.error(ex.getMessage());
        }
        return swStr;
    }
}
